package com.coastline.fruit.common.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 默认线程池工厂
 *
 * @author Coastline
 * @date 2025/1/10 22:28
 */
@Slf4j
public class CoastlineDefaultThreadFactory implements ThreadFactory {
    /**
     * 线程id编号
     */
    private final AtomicInteger threadNumber = new AtomicInteger(1);

    /**
     * ThreadGroup
     */
    private final ThreadGroup threadGroup;

    private String namePrefix;

    /**
     * Constructs a new {@code Thread}.  Implementations may also initialize
     * priority, name, daemon status, {@code ThreadGroup}, etc.
     *
     * @paramr a runnable to be executed by new thread instance
     * @return constructed thread, or {@code null} if the request to
     * create a thread is rejected
     */
    @Override
    public Thread newThread(Runnable run) {
        Thread thread = new Thread(threadGroup, run, namePrefix + "-thread-" + threadNumber.getAndIncrement(), 0);
        // 是否为守护线程
        if (thread.isDaemon()) {
            thread.setDaemon(false);
        }
        thread.setUncaughtExceptionHandler((t1, exception) -> log.error("failed to execute the thread", exception));
        return thread;
    }

    public CoastlineDefaultThreadFactory(String namePrefix) {
        SecurityManager securityManager = System.getSecurityManager();
        threadGroup = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
        this.namePrefix = namePrefix;
    }
}
